function bindFileTableEvents() {
    initializeFileTable();
}

function initializeFileTable() {
    loadFileData();

    document.getElementById('add-file-btn').addEventListener('click', submitNewFile);

    document.getElementById('files-tbody').addEventListener('click', function (event) {
        const target = event.target;

        if (target.classList.contains('view-file-btn')) {
            const filePath = target.getAttribute('data-path');
            const fileName = target.getAttribute('data-name');
            viewFile(filePath, fileName);
        }
    });
}

function loadFileData() {
    $.ajax({
        url: "http://localhost:8080/file/view",
        method: "GET",
        dataType: "json",
        success: function (response) {
            let files = response.data;
            let filesTbody = $("#files-tbody");
            filesTbody.empty();

            files.forEach(function (file) {
                filesTbody.append(`
                    <tr>
                        <td>${file.id}</td>
                        <td>${file.name}</td>
                        <td>${file.owner}</td>
                        <td>
                            <button class="btn btn-primary view-file-btn" data-path="${file.path}" data-name="${file.name}">查看文件</button>
                        </td>
                    </tr>
                `);
            });
        },
        error: function (error) {
            console.error("加载文件数据失败：", error);
        }
    });
}

function submitNewFile() {
    let formData = new FormData($('#add-file-form')[0]);
    $.ajax({
        url: "http://localhost:8080/file/upload",
        method: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function () {
            alert("文件添加成功");
            $('#add-file-modal').modal('hide');
            loadFileData(); // 重新加载文件数据
        },
        error: function (error) {
            console.error("文件添加失败：", error);
            alert("文件添加失败");
        }
    });
}

function viewFile(filePath, fileName) {
    $('#view-file-modal-label').text('查看文件: ' + fileName);

    var fileExtension = filePath.split('.').pop().toLowerCase();

    // 图片预览
    if (['jpg', 'jpeg', 'png', 'gif'].includes(fileExtension)) {
        renderImagePreview(filePath);
    }
    // 文本预览
    else if (['txt'].includes(fileExtension)) {
        renderTextPreview(filePath);
    }
    // PDF 预览
    else if (['pdf'].includes(fileExtension)) {
        renderPdfPreview(filePath);
    }
    // Word 预览
    else if (['doc', 'docx'].includes(fileExtension)) {
        renderWordPreview(filePath);
    }
    // 不支持预览的文件
    else {
        $('#view-file-content').html(`<div>暂不支持预览 ${fileName} 的类型。<br>文件路径：${filePath}</div>`);
    }

    $('#view-file-modal').modal('show');
}

function renderImagePreview(imageUrl) {
    let avatarURL = imageUrl ? '.' + imageUrl : './uploads/default_avatar.png';
    const content = `
        <img src="${avatarURL}" style="max-width: 100%; max-height: 400px;"/>
    `;
    $('#view-file-content').html(content);
}

function renderTextPreview(textUrl) {
    const adjustedTextUrl = '.' + textUrl;

    fetch(adjustedTextUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error('无法加载文本文件。');
            }
            return response.text();
        })
        .then(text => {
            const content = `<pre>${text}</pre>`;
            $('#view-file-content').html(content);
        })
        .catch(error => {
            const content = '<div>无法加载文本文件。</div>';
            $('#view-file-content').html(content);
            console.error("加载文本文件失败：", error);
        });
}
function renderPdfPreview(pdfUrl) {
    const adjustedPdfUrl = '.' + pdfUrl;
    const content = `
        <embed src="${adjustedPdfUrl}" style="width: 100%; height: calc(100vh - 150px);" type="application/pdf" />
    `;
    $('#view-file-content').html(content);
}

function renderWordPreview(wordUrl) {
    const adjustedWordUrl = '.' + wordUrl;
    const googleDocsViewer = `https://docs.google.com/viewer?url=${encodeURIComponent(location.origin + adjustedWordUrl)}&embedded=true`;

    const content = `
        <iframe src="${googleDocsViewer}" style="width: 100%; height: calc(100vh - 150px); border: 0;"></iframe>
    `;
    $('#view-file-content').html(content);
}